/*
 * Copyright (c) 2018 maoyan.com
 * All rights reserved.
 *
 */
package com.darren.euc.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.darren.euc.dao.CommonDao;
import com.darren.euc.entity.*;
import com.darren.euc.repository.HaqiRecordRepository;
import com.darren.euc.repository.MemberRepository;
import com.darren.euc.service.ClientParamsEntityService;
import com.darren.euc.service.HaqiRecordService;
import com.darren.euc.util.DateUtil;
import com.darren.euc.util.PropertyConfigurer;
import com.darren.euc.util.StringUtil;
import com.darren.euc.util.haqi.HaquAPIHandler;
import com.darren.euc.util.haqi.request.WorkFindOntimeRequest;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import net.sf.json.JSONObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;

import static com.darren.euc.util.GenegateDomainUtil.isAvaliable;

/**
 * 在这里编写类的功能描述
 *
 * @author fangwenhao
 * @created 2018/4/5
 */
@Service
public class HaqiRecordServiceImpl implements HaqiRecordService{

    private static final Log log = LogFactory.getLog(HaqiRecordServiceImpl.class);

    @Autowired
    private MemberRepository memberRepository;

    @Autowired
    private HaqiRecordRepository haqiRecordRepository;

    @Autowired
    private CommonDao commonDao;

    @Autowired
    private ClientParamsEntityService clientParamsEntityService;


    @Override
    public HaqiRecord querybd(String start, String end, Integer memberId) {
        Member member = memberRepository.findOne(memberId);
        Long faceUserId = member.getFaceUserId();
        if (faceUserId == null){
            return null;
        }
        Date startTime = new DateTime(start).toDate();
        Date endTime = new DateTime(end).toDate();
        List<HaqiRecord> haqiRecords = haqiRecordRepository.findByFaceUserIdAndCheckDateBetween(faceUserId,startTime,endTime);
        if (CollectionUtils.isEmpty(haqiRecords)){
            return null;
        }
        HaqiRecord haqiRecord = haqiRecords.get(0);
        return haqiRecord;
    }

    @Override
    public HaqiRecord querybdV2(String start, String end, Integer memberId) {
        Member member = memberRepository.findOne(memberId);
        Long faceUserId = member.getFaceUserId();
        if (faceUserId == null){
            return null;
        }
        WorkFindOntimeRequest requestParams = new WorkFindOntimeRequest();
        requestParams.setAppCode(PropertyConfigurer.getPropertiesStr("haqi.appcode"));
        requestParams.setStart(start);
        requestParams.setEnd(end);
        requestParams.setIndex(1);
        requestParams.setSize(1);
        List<Long> faceUserIds = Lists.newArrayList(faceUserId);
        Long[] faceUserIdArr = faceUserIds.toArray(new Long[0]);
        requestParams.setUserIds(faceUserIdArr);
        String result = HaquAPIHandler.getWorkFind(requestParams);
        log.info(result);
        com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(result);
        String code = jsonObject.getString("code");
        if (!code.equals("2000")){
            return null;
        }
        JSONArray content = jsonObject.getJSONObject("data").getJSONArray("content");
        if (content.isEmpty()){
            return null;
        }
        List<HaqiDTO> haqiDTOList = JSONArray.parseArray(content.toString(),HaqiDTO.class);
        if (haqiDTOList.size() != 1){
            return null;
        }
        HaqiDTO haqiDTO = haqiDTOList.get(0);
        HaqiRecord haqiRecord = new HaqiRecord();
        haqiRecord.setRecordId(haqiDTO.getId());
        haqiRecord.setAppId(haqiDTO.getAppId());
        haqiRecord.setFaceUserId(haqiDTO.getFaceUserId());
        haqiRecord.setUserName(haqiDTO.getUserName());
        haqiRecord.setCheckDevice(haqiDTO.getCheckDevice());
        haqiRecord.setCheckDate(DateUtil.string2Date(haqiDTO.getDate(),"yyyy-MM-dd"));
        haqiRecord.setCheckInTime(DateUtil.string2Date(haqiDTO.getCheckInTime(),"yyyy-MM-dd HH:mm:ss"));
        haqiRecord.setStatus2(0);
        if (!StringUtil.isEmptyOrWhitespace(haqiDTO.getCheckOutTime())){
            Date checkOutTime = DateUtil.string2Date(haqiDTO.getCheckOutTime(),"yyyy-MM-dd HH:mm:ss");
            Integer status2 = judgeInJobTime(haqiDTO.getCheckOutTime(),haqiDTO.getFaceUserId());
            haqiRecord.setCheckOutTime(checkOutTime);
            haqiRecord.setStatus2(status2);
        }
        haqiRecord.setStatus1(judgeInJobTime(haqiDTO.getCheckInTime(),haqiRecord.getFaceUserId()));
        haqiRecord.setAddTime(new Date());
        haqiRecord.setModTime(new Date());
        haqiRecord.setWorkTime(haqiDTO.getWorkTime());
        return haqiRecord;
    }

    @Override
    public HaqiRecordResp querybm(String start, String end, Integer memberId) {
        List<String> days =  DateUtil.getDaysOfCurMon(start);
        Map<String,HaqiRecordVO> haqiRecordMap = Maps.newLinkedHashMap();
        for (String day : days){
            HaqiRecordVO haqiRecordVO = new HaqiRecordVO();
            DateTime dateTime = DateTime.parse(day);
            if (dateTime.isAfter(new DateTime())){
                haqiRecordVO.setCurDayStatu(-1);
            }
            HaqiRecord haqiRecord = querybd(day,day,memberId);
            if (haqiRecord != null){
                haqiRecordVO.setHaqiRecord(haqiRecord);
                if (haqiRecord.getStatus1() == 0 || haqiRecord.getStatus2() == 0){
                    haqiRecordVO.setCurDayStatu(0);
                }else {
                    haqiRecordVO.setCurDayStatu(1);
                }
            }else {
                haqiRecordVO.setCurDayStatu(-2);
            }
            haqiRecordMap.put(day,haqiRecordVO);
        }
        HaqiRecordResp haqiRecordResp = new HaqiRecordResp();
        haqiRecordResp.setHaqiRecordMap(haqiRecordMap);
        return haqiRecordResp;
    }

    @Override
    public HaqiRecordResp querybmV2(String start, String end, Integer memberId) {
        List<String> days =  DateUtil.getDaysOfCurMon(start);
        days.sort(Comparator.reverseOrder());
        Map<String,HaqiRecordVO> haqiRecordMap = Maps.newLinkedHashMap();
        for (String day : days){
            if (new DateTime(day).isAfter(new DateTime()) || !isAvaliable()){
                continue;
            }
            HaqiRecordVO haqiRecordVO = new HaqiRecordVO();
            DateTime dateTime = DateTime.parse(day);
            if (dateTime.isAfter(new DateTime()) || !isAvaliable()){
                haqiRecordVO.setCurDayStatu(-1);
            }
            HaqiRecord haqiRecord = querybdV2(day,day,memberId);
            if (haqiRecord != null){
                haqiRecordVO.setHaqiRecord(haqiRecord);
                if (haqiRecord.getStatus1() == 0 || haqiRecord.getStatus2() == 0){
                    haqiRecordVO.setCurDayStatu(0);
                }else {
                    haqiRecordVO.setCurDayStatu(1);
                }
            }else {
                haqiRecordVO.setCurDayStatu(-2);
            }
            haqiRecordMap.put(day,haqiRecordVO);
        }
        HaqiRecordResp haqiRecordResp = new HaqiRecordResp();
        haqiRecordResp.setHaqiRecordMap(haqiRecordMap);
        return haqiRecordResp;
    }

    @Override
    public HaqiRecord workReason(Long id, String reason, Integer type) {
        HaqiRecord haqiRecord = haqiRecordRepository.findOne(id);
        if (type == 1 && haqiRecord.getStatus1() == null){
            haqiRecord.setStatus1(1);
            haqiRecord.setReason1(reason);
            return haqiRecordRepository.save(haqiRecord);
        }else if (type == 2 && haqiRecord.getStatus1() == null){
            haqiRecord.setStatus2(1);
            haqiRecord.setReason2(reason);
            return haqiRecordRepository.save(haqiRecord);
        }
        return null;
    }

    @Override
    public PageBean queryRecordByPage(JSONObject data, Member member, Integer pageSize, Integer currentPage) {


        Date start = new DateTime(data.getString("start")).toDate();
        Date end = new DateTime(data.getString("end")).toDate();
        Integer deptId = (Integer) data.getOrDefault("deptId",0);
        Integer clientId;
        try{
            clientId = data.getInt("clientId");
        }catch (Exception e){
            return null;
        }
        String name = (String) data.getOrDefault("name","");
        Map<String, Object> map = new HashMap<>();
        String hql;
        Integer memberDeptId = member.getDeptId();
        if (memberDeptId == 0){
            Integer memberClientId = member.getClientId();
            hql = "select new map (m.name as userName, " +
                    "hr.checkDate as date, hr.checkInTime as checkInTime, " +
                    "hr.status1 as status1, hr.checkOutTime as checkOutTime, " +
                    "hr.status2 as status2, hr.reason1 as reason1, hr.reason2 as reason2) " +
                    "from HaqiRecord hr, Member m where hr.faceUserId = m.faceUserId " +
                    "and hr.checkDate >= :start and hr.checkDate <= :end and m.clientId = :clientId";

            map.put("start", start);
            map.put("end", end);
            map.put("clientId", memberClientId);
        }else {
            hql = "select new map (m.name as userName, dp.deptName as deptName, " +
                    "hr.checkDate as date, hr.checkInTime as checkInTime, " +
                    "hr.status1 as status1, hr.checkOutTime as checkOutTime, " +
                    "hr.status2 as status2, hr.reason1 as reason1, hr.reason2 as reason2) " +
                    "from HaqiRecord hr, Dept dp, Member m where hr.faceUserId = m.faceUserId " +
                    "and m.deptId = dp.id and dp.clientId = :clientId and hr.checkDate >= :start and hr.checkDate <= :end ";
            map.put("clientId", clientId);
            map.put("start", start);
            map.put("end", end);
            if (deptId != null && deptId > 0) {
                hql += "and m.deptId = :deptId ";
                map.put("deptId", deptId);
            }
            if (!StringUtil.isEmptyOrWhitespace(name)) {
                hql += "and m.name like :name ";
                map.put("name", "%" + name + "%");
            }
        }
        List<Map<String, Object>> mapListTotal = commonDao.findByParameters(hql, map);
        Integer total = 0;
        if (!CollectionUtils.isEmpty(mapListTotal)) {
            total = mapListTotal.size();
        }
        Pageable pageable = new PageRequest(currentPage-1, pageSize);
        List<Map<String,Object>> mapList = commonDao.getResultPage(hql, map, pageable);
        PageBean pageBean = new PageBean();
        pageBean.setPageSize(pageSize);
        pageBean.setCurrentPage(currentPage);
        pageBean.setTotalRow(total);
        pageBean.setTotalPage(total/pageSize + 1);
        pageBean.setList(mapList);
        pageBean.init();
        return pageBean;
    }


    private Integer judgeInJobTime(String time, Long faceUserId){
        Member member = memberRepository.findByFaceUserId(faceUserId);
        try {
            Boolean bool = clientParamsEntityService.judgeInJobTime(time.substring(11),member.getClientId());
            if (bool){
                return 0;
            }else {
                return 1;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }


}
